import { _decorator, Animation, Component, Label, Node, Toggle } from 'cc';
import { GLOBALUtil } from './GlobalUtil';
import { GLOBALVar } from './GlobalVar';
const { ccclass, property } = _decorator;

type Notice = {
    msg: string,
    id: number,
    content: string
}

@ccclass('NoticeManager')
export class NoticeManager extends Component {
    @property({type: Node, tooltip: "NoticeNode"})
    private NoticeNode: Node = null;
    @property({type: Node, tooltip: "NoticePanel"})
    private NoticePanel: Node = null;
    @property({type: Node, tooltip: "NoticeContent"})
    private NoticeContent: Node = null;
    @property({type: Node, tooltip: "NoticeToggle"})
    private NoticeToggle: Node = null;

    private NoticeData: Notice = null;
    async onEnable() {
        try {
            this.NoticePanel.getComponent(Animation).play();
            if (this.NoticeData == null) {
                const response = await GLOBALUtil.getNotice() as Notice;
                this.NoticeData = response;

                const flag = localStorage.getItem(`isHideNotice_${this.NoticeData.id}`);
                this.NoticeToggle.getComponent(Toggle).isChecked = flag === "1";
                this.showNotice();
            }
        } catch (error) {
            console.error(error);
        }
    }
    start() {
        this.NoticeToggle.on(Toggle.EventType.TOGGLE, () => {
            const toggle = this.NoticeToggle.getComponent(Toggle);
            const key = `isHideNotice_${this.NoticeData.id}`
            const flag = toggle.isChecked ? "1" : "0";
            localStorage.setItem(key, flag);
        })
    }


    closeNode() {
        this.NoticeNode.active = false;
    }

    openNode() {
        this.NoticeNode.active = true;
    }

    showNotice() {
        this.NoticeContent.getComponent(Label).string = this.NoticeData.content;
    }

    
}


